﻿using System;
using System.Collections.Generic;
using System.Data;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using U8API.Pub;
using U8Login;
using UFIDA.U8.MomServiceCommon;

namespace U8API.Plugin
{
    public class DispatchlistPlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Dispatchapi";
        private static string constr = "";
        private string url = "";




        private bool GetCustJsPLM(clsLogin loginObj, MSXML2.IXMLDOMDocument2 domhead, MSXML2.IXMLDOMDocument2 dombody, int operation, ref string errMsg)
        {
            try
            {

                var datatable = Common.GetPlmUrl(constr, loginObj.get_cAcc_Id()).Tables[0];
                var datarow = datatable.Rows[0];
                url = datarow[1].ObjToString() + "IF_01?";

                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");      

                //判断是否第一次发货
                int dlid = tmphead.attributes.getNamedItem("dlid").nodeValue.ObjToInt32();//发货退货单主表标识
                string ddate = tmphead.attributes.getNamedItem("ddate").nodeValue.ObjToStringNull();//发货退货单日期
                string sql = @"select cinvcode from DispatchLists dls with (nolock) where dls.DLID = " + dlid + " and not exists (select 1 from DispatchLists dls2  with (nolock) where dls2.DLID != " + dlid + " and dls2.cInvCode = dls.cInvCode) ";
                DataTable dt = UFIDA.U8.DB.DbHelperSQL.QueryAsDT(sql, loginObj.UFDataConnstringForNet);
                if (dt!= null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr  in dt.Rows)
                    {                                    
                        Dictionary<string, string> dic = new Dictionary<string, string>();
                        dic.Add("itemid", dr["cinvcode"].ObjToString());
                        dic.Add("finishdate", DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
                        dic.Add("orgcode", loginObj.get_cAcc_Id());
                        //dic.Add("finishdate", DateTime.Now.ToString("yyyyMMddHHmm"));
                        var result = HttpHelper.PostDataToServerDic(url, dic, "application/x-www-form-urlencoded");
                        var apiresult = Common.DeserializeObject<ApiResponse>(result);
                        if (apiresult.successful != 0)
                        {
                            errMsg = apiresult.message;
                            return false;
                        }   
                    }
                    return true;
                }
                else
                {
                    return  false;
                } 
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("发货单PLM接口-dispatchlist", "GetCustJsPLM", e);
                throw e;
            }
          
        }
        /// <summary>
        /// 发货单
        /// </summary>
        /// <param name="login"></param>
        /// <param name="domhead"></param>
        /// <param name="dombody"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        private String GetCustJs(clsLogin login, MSXML2.IXMLDOMDocument2 domhead, MSXML2.IXMLDOMDocument2 dombody, int operation)
        {
            var datatable = Common.GetUrl(constr, login.get_cAcc_Id()).Tables[0];
            var datarow = datatable.Rows[0];
            url = datarow[1] + "Dispatchapi";                                                            
            MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");

            string dispathchCode = tmphead.attributes.getNamedItem("cdlcode").nodeValue.ObjToString();//发货单号
            int dlid = tmphead.attributes.getNamedItem("dlid").nodeValue.ObjToInt32();//发货退货单主表标识
            int breturnFlag = tmphead.attributes.getNamedItem("breturnflag").nodeValue.ObjToInt32();//退货标识-0 发 1 退
            int cbustype = tmphead.attributes.getNamedItem("cbustype").nodeValue.ObjToInt32();//业务类型
            string soTypeCode = tmphead.attributes.getNamedItem("cstcode").nodeValue.ObjToString();//销售类型
            string customerCode = tmphead.attributes.getNamedItem("ccuscode").nodeValue.ObjToString();//客户编码
            DateTime disDate = tmphead.attributes.getNamedItem("ddate").nodeValue.ObjToDate();//单据时间
            string bz = tmphead.attributes.getNamedItem("cexch_name").nodeValue.ObjToString();//币种 cexch_name 
            float exchangeRate = tmphead.attributes.getNamedItem("iexchrate").nodeValue.ObjToFloat();//汇率
            float taxRate = tmphead.attributes.getNamedItem("itaxrate").nodeValue.ObjToFloat();//税率 iTaxRate       

            string sql = @"select irowno,dlid,idlsid,autoid,csocode,isosid,iquantity,cinvcode,cwhcode," +
                         "iunitprice,itaxunitprice,imoney,isum,itax,inatunitprice,inatmoney,inatsum,inattax,cfree1,cfree2,cfree3,cfree4,cfree5,cfree6,cfree7,cfree8,cfree9,cfree10 " +
                         "from sale_DispToSaleVouch_B with(nolock) where dlid = '" + dlid + "'";

            var table = DbHelperSQL.Query(sql, constr, null).Tables[0];                 

            List<DispatchlistapiErp> dlist = new List<DispatchlistapiErp>();
            try
            {
                foreach (DataRow item in table.Rows)
                {
               
                    int StartFlag = 0;
                    DispatchlistapiErp d = new DispatchlistapiErp();
                    d.DispathchCode = dispathchCode; //发货单号
                    d.BreturnFlag = breturnFlag; //退货标识（0发 1退）
                    d.CBusType = cbustype; //业务类型
                    d.SoTypeCode = soTypeCode; //销售类型
                    d.CustomerCode = customerCode; //客户编号
                    d.DisDate = disDate; //单据时间
                    d.DisSeq = item["irowno"].ObjToInt32(); //发货行号
                    d.DisID = item["dlid"].ObjToInt32(); //发货单ID
                    d.DisDID = item["idlsid"].ObjToInt32();//autoid,idlsid 发货表体ID
                    d.DisQty = item["iquantity"].ObjToDecimal(); //发货数量
                    d.SoCode = item["csocode"].ObjToString(); //销售订单号
                    d.SoDID = item["isosid"].ObjToInt32(); //销售订单表体ID
                    d.CinvCode = item["cinvcode"].ObjToString(); //存货编码
                    d.WhoCode = item["cwhcode"].ObjToString(); //仓库编号
                    d.Status = StartFlag; //单据状态（0开启 1关闭）
                    d.Bz = bz; //币种
                    d.ExchangeRate = exchangeRate; //汇率
                    d.TaxRate = taxRate; //税率
                    d.OriPrice = item["iunitprice"].ObjToDecimal(); //原币单价
                    d.OriTaxPrice = item["itaxunitprice"].ObjToDecimal(); //原币含税单价
                    d.IOriSum = item["imoney"].ObjToDecimal();//iMoney 原币金额
                    d.IoriTaxSum = item["isum"].ObjToDecimal(); //原币价税合计
                    d.IOriTax = item["itax"].ObjToDecimal(); //原币税额
                    d.IlocalPrice = item["inatunitprice"].ObjToDecimal(); //本币单价
                    //d.IlocalTaxPrice = item["cwhcode"].ObjToDecimal();
                    d.ILocalSum = item["inatmoney"].ObjToDecimal(); //本币金额
                    d.ILocalTaxSum = item["inatsum"].ObjToDecimal(); //本币价税合计
                    d.IlocalTax = item["inattax"].ObjToDecimal(); //本币税额
                    d.CMemo = item["cfree1"] + "," + item["cfree2"] + "," +
                              item["cfree3"] + "," + item["cfree4"] + "," +
                              item["cfree5"] + "," + item["cfree6"] + "," +
                              item["cfree7"] + "," + item["cfree8"] + "," +
                              item["cfree9"] + "," + item["cfree10"];

              
                    dlist.Add(d);
                }

                ApiRequest req = new ApiRequest();
                req.data = dlist;
                req.orgcode = login.get_cAcc_Id();
                req.primarykey = dispathchCode;
                req.operation = operation;
                DebugWriteLog.WriteLine("发货单接口-dispatchlist", "GetCustJs", req.ToJson());
                return req.ToJson();
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("发货单接口-dispatchlist", "GetCustJs", e);
                throw e;
            }

        }


        public bool Update_After_PLM(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            bool js;
            try
            {                                                            
                js = GetCustJsPLM(login, domhead, dombody, 0, ref errMsg);     

                return js;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = ex.Message;
                DebugWriteLog.WriteLine("DispatchlistPlugin", "异常", ex);
            }
            return bresult;
        }


        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 2);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
        public bool Insert_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 0);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js;
            try
            {
                js = GetCustJs(login, domhead, dombody, 1);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
    }
}